package com.bc.trade.channel.kingpay;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bc.common.CommonEnum.OrderStatus;
import com.bc.common.CommonEnum.Resp;
import com.bc.common.PayType;
import com.bc.common.ThreadShare;
import com.bc.common.message.DFReq;
import com.bc.common.message.DFResp;
import com.bc.trade.channel.IChannel;
import com.bc.trade.channel.kingpay.utils.MerchantApiUtil;
import com.bc.trade.channel.kingpay.utils.PayConfigUtil;
import com.bc.trade.channel.kingpay.utils.SimpleHttpUtils;
import com.bc.trade.message.QueryCardInfoReq;
import com.bc.trade.message.QueryCardInfoResp;
import com.bc.trade.message.QueryOrderResp;
import com.bc.trade.message.QuickPayReq;
import com.bc.trade.message.QuickPayResp;
import com.bc.trade.message.QuickPaySetReq;
import com.bc.trade.message.QuickPaySetResp;
import com.bc.trade.message.RefundReq;
import com.bc.trade.message.RefundResp;
import com.bc.trade.message.SendSMSReq;
import com.bc.trade.message.SendSMSResp;
import com.bc.trade.message.UnionPayReq;
import com.bc.trade.message.UnionPayResp;
import com.bc.trade.model.TradeOrder;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSString;

public class KingpayChannel implements IChannel {

	private final String notifyUrl = "http://pay.lihaishop.com:8080/notify/kingpayCallback";
	
	String payKey = "62dca2482bf14b54848b9be4d749d8b0";
	String paySecret = "c0e6c80f080b437cba8b7b5722bca432";
	
	@Override
	public QueryOrderResp query(TradeOrder order) throws Exception {
		Map<String , String> paramMap = new HashMap<String , String>();

        paramMap.put("payKey", PayConfigUtil.readConfig("payKey")); // 商户支付Key
        paramMap.put("outTradeNo","1493781289373");//原交易订单号
        /////签名及生成请求API的方法///
        String sign = MerchantApiUtil.getSign(paramMap, PayConfigUtil.readConfig("paySecret"));
        paramMap.put("sign",sign);

        String payResult = SimpleHttpUtils.httpPost(PayConfigUtil.readConfig("payQueryUrl"), paramMap);

        System.out.println(payResult);

        JSONObject jsonObject = JSON.parseObject(payResult);
        Object resultCode = jsonObject.get("resultCode");//返回码
        Object errMsg = jsonObject.get("errMsg");//错误信息(请求失败时)

        if ("0000".equals(resultCode.toString())){//请求成功
            System.out.println("请求成功");
        }else{//请求失败
            System.out.println(errMsg);
        }
		return null;
	}

	@Override
	public QueryOrderResp dfQuery(TradeOrder order) throws Exception {
		Map<String , String> paramMap = new HashMap<String , String>();
		String url = "http://gateway.kingpay.top/proxyPayQuery/query";
        paramMap.put("payKey", payKey); // 商户支付Key
        paramMap.put("outTradeNo",order.getOrderNo());//原交易订单号
        /////签名及生成请求API的方法///
        String sign = MerchantApiUtil.getSign(paramMap, paySecret);
        paramMap.put("sign",sign);
        String payResult = SimpleHttpUtils.httpPost(url, paramMap);
        System.out.println(payResult);
        JSONObject jsonObject = JSON.parseObject(payResult);
        Object resultCode = jsonObject.get("resultCode");//返回码
        Object errMsg = jsonObject.get("errMsg");//错误信息(请求失败时)

        if ("0000".equals(resultCode.toString())){//请求成功
            System.out.println("请求成功");
        }else{//请求失败
            System.out.println(errMsg);
        }
		return null;
	}

	// 打款状态要以查询结果为准，根据 remitStatus 判断打款状态
	@Override
	public DFResp df(DFReq req, TradeOrder order) throws Exception {
		String url = "http://gateway.kingpay.top/accountProxyPay/initPay";
		DFResp rsp = new DFResp(req);
		
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("payKey", payKey);// 商户支付Key
		paramMap.put("outTradeNo", order.getOrderNo());
		paramMap.put("orderPrice", new DecimalFormat("0.00").format(order.getAmount()/100.00)); //支付金额
		// T0（T0 出款）
		// T1（T1 出款）
		paramMap.put("proxyType", "T0");
        paramMap.put("productType","B2CPAY"); //产品类型 B2CPAY  WEIXIN  ALIPAY
        paramMap.put("bankAccountType","PRIVATE_DEBIT_ACCOUNT");//PRIVATE_DEBIT_ACCOUNT 对私借记卡  PUBLIC_ACCOUNT 对公
        //paramMap.put("phoneNo",req.getPhoneNo()); //代付银行手机号
        //paramMap.put("certType","IDENTITY");//收款人证件类型 IDENTITY 身份证
        //paramMap.put("certNo",req.getCertsNo());  //代付证件号码
        
        paramMap.put("receiverName",req.getAccountName());   //账户名 收款人账户名
        
        paramMap.put("receiverAccountNo",req.getAccountCardNo());//银行账号
        //paramMap.put("bankClearNo",req.getBankSettleNo());//清算行行号
        //paramMap.put("bankName",req.getBankName());////开户行名称
        paramMap.put("bankCode",req.getBankType()); //联行号（简称）
        //paramMap.put("bankBranchNo","xxxxx");//代付开户银行支行行号
        //paramMap.put("bankBranchName","中国建设银行股份有限公司xxxx支行");//代付开户行支行名称
        //paramMap.put("province","河北省");//代付开户行省份
        //paramMap.put("city","沧州市");//代付开户行城市

        /////签名及生成请求API的方法///
        String sign = MerchantApiUtil.getSign(paramMap, paySecret);
        paramMap.put("sign",sign);
        
		String reqText = FSString.convertMapToUrlParameter(paramMap);
		System.out.println("请求发送报文：-->[" + reqText + "]");
		String rspJson = FSHttp.postFormString(url, reqText, "UTF-8");
		System.out.println("接收响应报文：<--[" + rspJson + "]");
		
        JSONObject map = JSON.parseObject(rspJson);
        String resultCode = map.getString("resultCode");//返回码
        String errMsg = map.getString("errMsg");//错误信息(请求失败时)
		if ("0000".equals(resultCode)) {
			// 下单成功
			order.setRespCode(Resp.InProcess.getCode());
			order.setRespMsg(Resp.InProcess.getMsg());
			// 验签
//			hmac = map.getString("hmac");
//			map.remove("hmac");// 返回数据签名不包含签名数据
//			if (Objects.equals(hmac, MerchSdkSign.getSign(map, signKey))) {
//				rsp.setType("1");
//				rsp.setUrl(map.getString("qrCodeUrl"));
//				rsp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
//			} else {
//				rsp.setCodeAndMsg(Resp.Fail.getCode(), "通道验证失败");
//			}
			
			rsp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
		} else {
			order.setRespCode(Resp.Fail.getCode());
			order.setRespMsg(errMsg);
			order.setOrderStatus(OrderStatus.Fail.getValue());
			rsp.setCodeAndMsg(Resp.Fail.getCode(), "失败CH(" + resultCode + "-" + errMsg + ")");
		}
		return rsp;
	}

	@Override
	public UnionPayResp unionpay(UnionPayReq req, TradeOrder order) throws Exception {
		UnionPayResp rsp = new UnionPayResp(req);
		String url = "";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("payKey", payKey);// 商户支付Key
		paramMap.put("orderPrice", new DecimalFormat("0.00").format(order.getAmount()/100.00)); //支付金额
		paramMap.put("outTradeNo", order.getOrderNo());
		if (PayType.UNION_PAY.equals(req.getPayType())) {
			//	B2CT1 支付 50000101
			//	B2CT0 支付 50000103
			//	B2CZ1 支付 50000104
			paramMap.put("productType","50000101");
			url = "http://gateway.kingpay.top/b2cPay/initPay";
		} else if (PayType.UNION_PAY_SUB.equals(req.getPayType())) {
			// 网关快捷支付 T1 支付 90000101
			// 网关快捷支付 T0 支付 90000103
			paramMap.put("productType","90000101");
			paramMap.put("bankAccountNo",req.getCardNo());
			url = "http://gateway.kingpay.top/gatewayQuickPay/initPay";
		}
		paramMap.put("orderTime", datetimeToNumber(order.getCreateTime()));
		paramMap.put("productName", order.getGoodsName());// 商品名称
		paramMap.put("orderIp", ThreadShare.ClientIP.get());
		paramMap.put("bankCode", req.getBankType());//银行编码
		if ("0".equals(req.getCardType())) {
			paramMap.put("bankAccountType", "PRIVATE_DEBIT_ACCOUNT");
		} else {
			paramMap.put("bankAccountType", "PRIVATE_CREDIT_ACCOUNT");
		}
		paramMap.put("returnUrl", req.getCallbackUrl());
		paramMap.put("notifyUrl", notifyUrl);
		//mobile 移动端（当为手机端时此参数不为空值为1）
		paramMap.put("remark", req.getRemark());
		///// 签名及生成请求API的方法///
		String sign = MerchantApiUtil.getSign(paramMap, paySecret);
		paramMap.put("sign", sign);
		
		String reqText = FSString.convertMapToUrlParameter(paramMap);
		System.out.println("请求发送报文：-->[" + reqText + "]");
		String rspText = FSHttp.postFormString(url, reqText, "UTF-8");
		System.out.println("接收响应报文：<--[" + rspText + "]");
		
		// B2C及网关快捷都是返回一个网页
		rsp.setType("0");
	    rsp.setHtml(rspText);
		order.setRespCode(Resp.InProcess.getCode());
		order.setRespMsg(Resp.InProcess.getMsg());
		rsp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
		return rsp;
	}

	@Override
	public QuickPaySetResp quickPaySet(QuickPaySetReq req, TradeOrder order) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public QuickPayResp quickPay(QuickPayReq req, TradeOrder order) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SendSMSResp sendSMS(SendSMSReq req) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public QueryCardInfoResp queryCardInfo(QueryCardInfoReq req) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RefundResp refund(RefundReq req, TradeOrder refundOrder, TradeOrder orignOrder) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	private String datetimeToNumber(String datetime) {
		char[] chars = new char[14];
		chars[0] = datetime.charAt(0);
		chars[1] = datetime.charAt(1);
		int index = 2;
		for(int i=2; i<datetime.length()-1; i+=3) {
			chars[index] = datetime.charAt(i);
			index++;
			chars[index] = datetime.charAt(i+1);
			index++;
		}
		return new String(chars);
	}

}

